package org.shuma.goods.utils;

import org.springframework.beans.BeanUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhao haitao
 * @date 2024/06/17 11:32 AM
 */
public class BeanCopyUtils {
    private BeanCopyUtils() {
    }
    public static <V> V copyBean(Object source, Class<V> clazz) {
        if (Objects.isNull(source)) return null;
        //创建目标对象
        V result;
        try {
            result = clazz.newInstance();
            //实现属性copy
            BeanUtils.copyProperties(source, result);
        } catch (Exception e) {
            throw new RuntimeException("bean copy error");
        }
        //返回结果
        return result;
    }

    public static <O, V> List<V> copyBeanList(List<O> list, Class<V> clazz) {
        if (list.isEmpty()) {
            return Collections.emptyList();
        }
        return list.stream()
                .map(o -> copyBean(o, clazz))
                .collect(Collectors.toList());
    }
}